/**
 * @author Evgeny Sorokin
 */
Ext.define('USocial.controller.MarkersPlace',{
	extend : 'Ext.app.Controller',
	
	config : {
		stores : ['FriendsStore'],
		refs : {
			uMap : 'uMap'
		},
		control : {
			uMap : {
				'initialize' : 'onMapInit'
			}
		}
	},
	
	onMapInit : function(){
		var me = this;
		
		var uMap = me.getUMap();
		var map = uMap.getMap();
		
		var friendsStore = Ext.getStore('FriendsStore'/*'FriendsAppUsersStore'*/);
		var appUserStore = Ext.getStore('AppUserStore');
		
		var appUserMarker = new google.maps.Marker({
			title : 'You are here',
			map : map
		});

		var markerMapping = {};
		
		friendsStore.on('updaterecord', function(store, friend, newIndex, oldIndex, modifiedFieldNames, modifiedValues, eOpts){
			var changes = friend.getChanges();
			var marker = markerMapping[friend.get('uid')];
			if(!marker){
				marker = markerMapping[friend.get('uid')] = new google.maps.Marker({
					icon : friend.get('photo_50'),
					position : new google.maps.LatLng(friend.lat, friend.lng),
					title : friend.get('first_name')+' '+friend.get('last_name'),
					map : map
				});
			}
			if(changes.lat || changes.lng){
				marker.setPosition(new google.maps.LatLng(friend.get('lat'), friend.get('lng')));
			}
			if(changes['photo_50']){
				marker.setIcon(friend.get('photo_50'));
			}
		});
		
		appUserStore.on('updaterecord', function(store, appUser, newIndex, oldIndex, modifiedFieldNames, modifiedValues, eOpts){
			var changes = appUser.getChanges();
			if(changes.lat || changes.lng){
				appUserMarker.setPosition(new google.maps.LatLng(appUser.get('lat'), appUser.get('lng')));
			}
		});
	}
	
});